// $URL: http://mingw-lib.googlecode.com/svn/trunk/working/4u_dump/widget.cpp $
// $Rev: 89 $
// $Author: akio.miyoshi $
// $Date:: 2010-05-19 06:08:48 +0000#$

#include "widget.h"
#include "ui_widget.h"
#include <QtCore>
#include <QtGui>
#include <QtNetwork>
#include <QtSql>
#include <QtXml>
#include <QtWebKit>

#include "xmlutil.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QWidget::setWindowFlags(Qt::WindowStaysOnTopHint); // top most
    nam = new NetworkAccessManager();

    ////ui->webView->setUrl(QUrl("qrc:/form.html"));
    connect(ui->webView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject1()));
    connect(ui->webView_2->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject2()));
    int v_webView_width = 400;
    ui->webView->setMinimumWidth(v_webView_width);
    ui->webView->setMaximumWidth(v_webView_width);

    ui->webView->setContextMenuPolicy(Qt::NoContextMenu);
    ui->webView_2->setContextMenuPolicy(Qt::NoContextMenu);

    QList<QAction *> v_action_list = ui->webView->actions();
    foreach(QAction *v_action, v_action_list)
    {
        ui->webView->removeAction(v_action);
    }
    resize(800, 400);
    QSqlDatabase m_db = QSqlDatabase::addDatabase("QODBC");
    m_db.setDatabaseName(
            "DRIVER={Microsoft Access Driver (*.mdb)};FIL={MS Access};DBQ=../4u_dump.mdb"
            );
    if (!m_db.open())
    {
        qDebug() << "ng";
        return;
    }
    else
    {
        qDebug() << "ok";
    }
    QSqlQuery query;
    QString sql =
            "create table tbl_4u("
            " id text"
            ",title text"
            ",pubdate datetime"
            ",primary key(id)"
            ")"
            ;
    qDebug() << sql;
    query.exec(sql);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void Widget::populateJavaScriptWindowObject1()
{
    ui->webView->page()->mainFrame()->addToJavaScriptWindowObject("formExtractor", this);
}

void Widget::populateJavaScriptWindowObject2()
{
    ui->webView_2->page()->mainFrame()->addToJavaScriptWindowObject("formExtractor", this);
}

void Widget::setDesktopFile(QFile &file, QString name)
{
    QString dirPath =
            QDesktopServices::storageLocation(
                    QDesktopServices::DesktopLocation);
    QDir dir(dirPath);
    QString filePath = dir.filePath(name);
    file.setFileName(filePath);
}

void Widget::saveDesktopFile(QString name, QByteArray bytes)
{
    QFile file;
    setDesktopFile(file, name);
    qDebug() << file.fileName();
    file.open(QIODevice::WriteOnly | QIODevice::Truncate);
    file.write(bytes);
}

void Widget::backupXmlBody(QByteArray bytes)
{
    saveDesktopFile("body.txt", bytes);
    QByteArray v_formated = XmlUtil::formatXml(bytes);
    saveDesktopFile("body2.txt", v_formated);
    //qDebug() << QString::fromUtf8(v_formated.constData());
}

int Widget::parseXmlFor4U(QByteArray &xml, QList<Rec4U> &result)
{
    result.clear();
    QDomDocument domDocument;
    if(!XmlUtil::setXmlContent(domDocument, xml))
    {
        qDebug() << "xml parse error!";
        return 0;
    }
    QDomElement root = domDocument.documentElement();
    qDebug() << root.tagName();
    QDomElement v_channel = root.firstChildElement("channel");

    QDomNodeList v_link_list = v_channel.elementsByTagNameNS("http://www.w3.org/2005/Atom", "link");
    for (int i=0; i<v_link_list.count(); i++)
    {
        QDomElement v_link = v_link_list.at(i).toElement();
        qDebug() << "[v_link.rel]" << v_link.attribute("rel");
    }

    QDomNodeList v_item_list = v_channel.elementsByTagNameNS("", "item");
    qDebug() << "v_item_list.count()" << v_item_list.count();

    for (int i=0; i<v_item_list.count(); i++)
    {
        Rec4U rec4u;
        QDomElement v_item = v_item_list.at(i).toElement();
        rec4u.title = v_item.firstChildElement("title").text();
        rec4u.link = v_item.firstChildElement("link").text();
        rec4u.guid = v_item.firstChildElement("guid").text();
        //[rec4u.key]
        rec4u.key = QString(rec4u.guid);
        rec4u.key.replace("http://4u.straightline.jp/image/", "");
        rec4u.pubDate = v_item.firstChildElement("pubDate").text();
        //rec4u.description = v_item.firstChildElement("description").text();
        //[rec4u.media:content]
        QDomNodeList v_content_list = v_item.elementsByTagNameNS("http://search.yahoo.com/mrss", "content");
        QDomElement v_content = v_content_list.at(0).toElement();
        rec4u.media_content = v_content.attribute("url");
        //[rec4u.media:thumbnail]
        QDomNodeList v_thumb_list = v_item.elementsByTagNameNS("http://search.yahoo.com/mrss", "thumbnail");
        QDomElement v_thumb = v_thumb_list.at(0).toElement();
        rec4u.media_thumbnail = v_thumb.attribute("url");
        //[rec4u.media_bitmap]
        rec4u.media_bitmap = QString(rec4u.media_thumbnail);
        rec4u.media_bitmap.replace("/m/m_", "/l/l_");
        qDebug() << "[rec4u]" << rec4u;

        result.append(rec4u);

        //this->ui->columnView;
    }
    return result.size();
}

QDateTime Widget::parseDateTime4U(QString pubDateStr)
{
    QString v_time1 = QString(pubDateStr);
    v_time1 = v_time1.mid(5);
    v_time1.replace(" GMT", "");
    v_time1.replace(" Jan ", "/01/");
    v_time1.replace(" Feb ", "/02/");
    v_time1.replace(" Mar ", "/03/");
    v_time1.replace(" Apr ", "/04/");
    v_time1.replace(" May ", "/05/");
    v_time1.replace(" Jun ", "/06/");
    v_time1.replace(" Jul ", "/07/");
    v_time1.replace(" Aug ", "/08/");
    v_time1.replace(" Sep ", "/09/");
    v_time1.replace(" Oct ", "/10/");
    v_time1.replace(" Nov ", "/11/");
    v_time1.replace(" Dec ", "/12/");
    v_time1.replace("/", " ");
    qDebug() << "v_time1" << v_time1;
    QDateTime v_result = QDateTime::fromString(v_time1, "dd MM yyyy HH:mm:ss");
    qDebug() << v_result;
    return v_result;

}

int Widget::addPageFor4U(int pageNo)
{
    QUrl v_url;
    v_url.setUrl(
            QString::fromLatin1("http://4u.straightline.jp/rss?page=%1")
            .arg(pageNo)
            );
    QByteArray v_xml = nam->doGet(v_url);
    backupXmlBody(v_xml);

    QList<Rec4U> v_result;
    parseXmlFor4U(v_xml, v_result);
    qDebug() << v_result.size();
#if 0x0
    for (int i=0; i<v_result.size(); i++)
    {
        const Rec4U &v_rec = v_result.at(i);
        QString v_title = Qt::escape(v_rec.title);
        QString v_html_part = QString("<img src=\"%1\" onclick=\"javascript:formExtractor.submit2('%2');\" />%3<br />\n")
                              .arg(v_rec.media_thumbnail)
                              .arg(v_rec.media_bitmap)
                              .arg(v_title);
        QWebFrame *v_frame = this->ui->webView->page()->mainFrame();
        QWebElement v_mydiv = v_frame->findFirstElement("#mydiv");
        v_mydiv.appendInside(
                QString("<img src='http://static.straightline.jp/html/found/static/upload/m/m_%1.jpg' "
                        "onclick=\"javascript:formExtractor.submit2('%1');\" />"
                        "<br />\n"
                        "%2")
                .arg(v_rec.key).arg(v_title)
                             );
        qDebug() << v_rec.pubDate;
        QDateTime v_pubDate = parseDateTime4U(v_rec.pubDate);
        QSqlQuery query;
        query.prepare("insert into tbl_4u (id, title, pubdate) "
                      "values (:id, :title, :pubdate)");
        query.bindValue(":id", v_rec.key);
        query.bindValue(":title", v_rec.title);
        query.bindValue(":pubdate", v_pubDate);
        query.exec();
    }
#endif
    return v_result.size();
}

int Widget::addDataFor4U(int pageNo)
{
    QUrl v_url;
    v_url.setUrl(
            QString::fromLatin1("http://4u.straightline.jp/rss?page=%1")
            .arg(pageNo)
            );
    QByteArray v_xml = nam->doGet(v_url);
    //backupXmlBody(v_xml);

    QList<Rec4U> v_result;
    parseXmlFor4U(v_xml, v_result);
    qDebug() << v_result.size();
    for (int i=0; i<v_result.size(); i++)
    {
        const Rec4U &v_rec = v_result.at(i);
        QDateTime v_pubDate = parseDateTime4U(v_rec.pubDate);
        QSqlQuery query;
        query.prepare("insert into tbl_4u (id, title, pubdate) "
                      "values (:id, :title, :pubdate)");
        query.bindValue(":id", v_rec.key);
        query.bindValue(":title", v_rec.title);
        query.bindValue(":pubdate", v_pubDate);
        query.exec();
    }
    return v_result.size();
}

void Widget::on_pushButton_clicked()
{
    this->ui->pushButton->setEnabled(false);
    QString v_html = "<div id=\"mydiv\">\n</div>";
    this->ui->webView->setHtml(v_html);

    //addPageFor4U(1);
    //for(int i=0; i<5; i++)
    for(int i=0; i<10; i++)
    {
        addPageFor4U(i+1);
    }
    this->ui->pushButton->setEnabled(true);
}

void Widget::on_pushButton_2_clicked()
{
#if 0x0
    for(int i=0; i<100; i++)
    {
        addDataFor4U(i+1);
    }
#endif
    QList<QByteArray> v_support_list = QImageWriter::supportedImageFormats();
    foreach(QByteArray v_support, v_support_list)
    {
        qDebug() << "[v_support]" << v_support;
    }
    QPixmap pixmap("../thumb.jpg");
    QByteArray bytes;
    QBuffer buffer(&bytes);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer, "BMP"); // writes pixmap into bytes in PNG format

    QSqlQuery insertImage;
    insertImage.prepare("INSERT INTO tbl00 ( a ) VALUES ( ? )");
    insertImage.addBindValue( bytes );
    insertImage.exec();
}

void Widget::submit()
{
    qDebug() << "submit()";
}

void Widget::submit2(QString a_url)
{
    qDebug() << "submit2()" << a_url;
    QString v_html = QString("<img src=\"http://static.straightline.jp/html/found/static/upload/l/l_%1.jpg\" />").arg(a_url);
    v_html += QString("<a href='http://4u.straightline.jp/image/%1'>%1</a>").arg(a_url);
    qDebug() << "[v_html]" << v_html;
    this->ui->webView->setHtml(v_html);
}

void Widget::on_pushButton_3_clicked()
{
    QFile v_js_file;
    v_js_file.setFileName(":/4u_list.js");
    v_js_file.open(QIODevice::ReadOnly);
    QByteArray v_js_content = v_js_file.readAll();
    QString v_js_string = QString::fromUtf8(v_js_content.constData());
    qDebug() << "[v_js_string]" << v_js_string;
    QString v_html;
    v_html += "<html>\n";
    v_html += "<head>\n";
    //v_html += "<link rel='stylesheet' href=':/4u_list.css' type='text/css' />\n";
#if 0x0
    v_html += "<script type='text/javascript' src='qrc:/script/js_list.js' charset='uft-8' />\n";
    //v_html += "<script type=\"text/javascript\" src=\"qrc:/js_list.js\" />\n";
#else
    v_html += "<script type='text/javascript'>\n";
    v_html += "<!--\n";
    v_html += v_js_string;
    v_html += "-->\n";
    v_html += "</script>\n";
#endif
    v_html += "<link rel='stylesheet' href='qrc:/4u_list.css' type='text/css' />\n";
    v_html += "</head>\n";
    v_html += "<body>\n";
    v_html += "<div id=\"mydiv\">\n</div>\n";
    v_html += "</body>\n";
    v_html += "</html>\n";
    qDebug() << v_html;
    this->ui->webView_2->setHtml(v_html);

    QSqlQuery query;
    query.exec("SELECT id, title FROM tbl_4u ORDER BY pubdate DESC");
    int counter = 0;
    while(query.next())
    {
        QString v_id = query.value(query.record().indexOf("id")).toString();
        qDebug() << "[v_id]" << v_id;
        QString v_thumb_m = QString("http://static.straightline.jp/html/found/static/upload/m/m_%1.jpg")
                            .arg(v_id);
        qDebug() << query.record().indexOf("title");
        QString v_title = query.value(query.record().indexOf("title")).toString();
        qDebug() << "[v_title(1)]" << v_title;
        v_title = Qt::escape(v_title);
        qDebug() << "[v_title(2)]" << v_title;

        QWebFrame *v_frame = this->ui->webView_2->page()->mainFrame();
        QWebElement v_mydiv = v_frame->findFirstElement("#mydiv");

        QString v_append =
                QString(
                        "<div class='pictOuter' id='outer_%2'>\n"
                        "    <img src='%1' class='pictBody' id='%2' title='%3' onclick='"
                        "formExtractor.submit2(\"%2\")'"
                        " />\n"
                        "    <div class='pictDelete'>\n"
                        "        <img src='qrc:/closetab.png' onclick='javascript:fn_del_image(\"%2\");"
                        "' />\n"
                        "    </div>\n"
                        "</div>\n"
                        ).arg(v_thumb_m).arg(v_id).arg(v_title)
                ;

        qDebug() << v_append;

        v_mydiv.appendInside(v_append);
        counter++;
        if (counter >= 30) return;
        //if (counter > 100) return;
    }
}

void Widget::on_pushButton_4_clicked()
{
}
